<template>
  <div class="course-content">
    <van-form>
      <div class="input-button-container">
        <van-field
          v-model="examination_date"
          label="检查日期"
          readonly
          clickable
          @click="showDatePicker = true"
          required
          placeholder="请选择检查日期"
          class="field-input"
        ></van-field>
        <van-button type="primary" @click="loadData" class="search-button">查询预约情况</van-button>
      </div>
      <van-popup v-model="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="examination_date"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirm"
          @cancel="showDatePicker = false"
        ></van-datetime-picker>
      </van-popup>
    </van-form>
    <van-list v-if="list.length > 0" :finished="finished" @load="onLoad">
      <van-cell
        v-for="item in list"
        :key="item.id"
        :title="item.patientName"
        :label="`预约号: ${item.patientRegistrationNumber} | 联系电话: ${item.contactPhone}`"
        :value="`检查日期: ${new Date(item.examinationDate).toLocaleDateString()}`"
      ></van-cell>
    </van-list>
  </div>
</template>

<script>

import { getExaminationDate } from '@/services/mother'

export default {
  name: 'Course',
  data () {
    return {
      list: [],
      examination_date: null, // 用于 v-model 绑定日期选择器的值
      examination_date_text: '', // 用于显示日期选择器的文本值
      showDatePicker: false, // 控制日期选择器弹出层的显示与隐藏
      minDate: new Date(), // 最小日期为今天
      maxDate: new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000),
      timeRange: '13:00-17:00' // 固定的时间范围
    }
  },

  methods: {
    onConfirm (value) {
      const formattedDate = this.formatDate(value)
      this.examination_date_text = `${formattedDate} ${this.timeRange}` // 更新显示的文本值
      this.examination_date = formattedDate
      this.showDatePicker = false // 关闭弹出层
    },
    formatDate (date) {
      const year = date.getFullYear()
      const month = (1 + date.getMonth()).toString().padStart(2, '0') // 月份从0开始，所以需要+1，并使用padStart补0
      const day = date.getDate().toString().padStart(2, '0') // 使用padStart补0
      return `${year}-${month}-${day}`
    },
    async loadData () {
      if (!this.examination_date_text) {
        this.$toast.fail('请选择日期')
        return
      }
      const response = await getExaminationDate(this.examination_date)
      if (response.data.code === 200) {
        this.list = response.data.data
      } else {
        console.error('获取数据失败', response.data.msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.input-button-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.field-input {
  flex-grow: 1;
  margin-right: 8px; /* Adjust spacing between field and button */
}

.search-button {
  flex-shrink: 0; /* Prevents the button from shrinking */
}
</style>
